package com.huawei.pet.service.impl;

import com.huawei.basic.exception.BusinessException;
import com.huawei.basic.service.IBaiduAiAuditService;
import com.huawei.basic.util.CodeGenerateUtils;
import com.huawei.basic.util.DistanceUtil;
import com.huawei.basic.util.LoginContext;
import com.huawei.basic.util.PageList;
import com.huawei.order.domain.OrderPetAcquisition;
import com.huawei.order.mapper.OrderPetAcquisitionMapper;
import com.huawei.org.domain.Employee;
import com.huawei.org.domain.Shop;
import com.huawei.org.mapper.EmployeeMapper;
import com.huawei.org.mapper.ShopMapper;
import com.huawei.pet.domain.Pet;
import com.huawei.pet.domain.SearchMasterMsg;
import com.huawei.pet.domain.SearchMasterMsgAuditLog;
import com.huawei.pet.dto.MsgDto;
import com.huawei.pet.mapper.PetMapper;
import com.huawei.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.huawei.pet.mapper.SearchMasterMsgMapper;
import com.huawei.pet.query.SearchMasterMsgQuery;
import com.huawei.pet.service.ISearchMasterMsgService;
import com.huawei.basic.service.impl.BaseServiceImpl;
import com.huawei.user.domain.Logininfo;
import com.huawei.user.domain.User;
import com.huawei.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;


    /**
     * 前台发布寻主消息
     * @param searchMasterMsg
     * @param request
     */
    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //获取审核人
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());

        //保存发布信息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);

        //自动审核
        String auditText = searchMasterMsg.getName()+" "+searchMasterMsg.getTitle()+searchMasterMsg.getAddress();
        Boolean boo1 = baiduAiAuditService.textAudit(auditText);

        String resources = searchMasterMsg.getResources();//图片，视频
        Boolean boo2 = baiduAiAuditService.imageAudit(resources);

        if (boo1 && boo2){
            // 1 自动审核通过，分发给店铺，并发送短信或者邮件消息。分发不成功放入寻主池。
            //1)查询所有店铺
            List<Shop> shops = shopMapper.loadAll();
            //2)从中获取满足条件店铺 小于50公里
            Shop nearestShop = DistanceUtil
                    .getNearestShop(DistanceUtil.getPoint(searchMasterMsg.getAddress()), shops);
            //3）如果找到了，把消息分给店铺并发消息
            if (nearestShop!=null){
                searchMasterMsg.setShopId(nearestShop.getId());
                //@TODO 发送邮件或者短信
                System.out.println("你来生意了！赶快去接客！"+searchMasterMsg.getTitle());
            }
            //4)如果没有找到放入寻主池-不做任何处理
            //5)修改状态
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核通过！");
            searchMasterMsgMapper.update(searchMasterMsg);

            //6)审核通过也要记录日志
            SearchMasterMsgAuditLog auditLog = new SearchMasterMsgAuditLog();
            auditLog.setMsgId(searchMasterMsg.getId());
            auditLog.setState(1);
            auditLog.setNote("审核通过！");
            searchMasterMsgAuditLogMapper.save(auditLog);
        }else{
            //2 如果审核失败，驳回。用户就可以在前台修改完成继续提交审核、
            searchMasterMsg.setState(0);
            searchMasterMsg.setNote("审核失败，内容存在非法信息");
            searchMasterMsgMapper.update(searchMasterMsg);

            //记录日志
            SearchMasterMsgAuditLog auditLog = new SearchMasterMsgAuditLog();
            auditLog.setMsgId(searchMasterMsg.getId());
            auditLog.setState(0);
            auditLog.setNote("审核失败，内容存在非法信息");
            searchMasterMsgAuditLogMapper.save(auditLog);
            throw new BusinessException("审核失败，内容存在非法信息");
        }
    }


    /**
     * 用户想查看自己的寻主信息状态
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> userSearchMasterMsg(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }


    /**
     * 寻主信息状态 - 待处理
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        Logininfo logininfo = LoginContext.getLoginUser(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id() !=null ){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }


    /**
     * 拒单
     * @param msgId
     */
    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.reject(msgId);
    }


    /**
     * 接单
     * @param msgDto
     */
    @Override
    public void accept(MsgDto msgDto) {
        Long empId = msgDto.getHandler();
        Long msgId = msgDto.getMsgId();
        String note = msgDto.getNote();

        //1.校验：当前寻主消息是否已经被接单了
        OrderPetAcquisition orderTem = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if(orderTem != null){
            throw new BusinessException("订单正在处理，请耐心等待!!!");
        }

        //1.创建宠物对象
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2pet(searchMasterMsg);
        petMapper.save(pet);

        //2.创建收购单
        OrderPetAcquisition order = buildOrder(pet,searchMasterMsg,empId);
        orderPetAcquisitionMapper.save(order);

        //3.发短信或邮件告诉收购人在规定时间之内去收购宠物
        System.out.println("你有新的订单，请在规定时间内去收购宠物");

    }


    /**
     * 创建订单
     * @param pet msg empId
     * @return
     */
    private OrderPetAcquisition buildOrder(Pet pet, SearchMasterMsg msg, Long empId) {

        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getTitle());
        //两天之后的此刻就是最后收购时间 - 自动通过定时器取消
        long timeTem = System.currentTimeMillis() + 2*24*60*60*1000;
        order.setLastcomfirmtime(new Date(timeTem));
        order.setState(0);//待处理
        order.setPrice(new BigDecimal(msg.getPrice()));
        //paytype//在处理订单时才处理
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }


    /**
     * 寻主信息转成宠物 - searchMasterMsg2pet
     * @param msg
     * @return
     */
    private Pet searchMasterMsg2pet(SearchMasterMsg msg) {

        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice().toString());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }

}
